import React, {useEffect, useRef, useState} from 'react';
import * as echarts from 'echarts';
import {reqGetEchartsArticleList} from "../../../../api/backStage/echarts";


const ArtcileChart = () => {
    const chartRef = useRef(null);
    const [echartsArr, setEchartsArr] = useState([])
    let option = {
        tooltip: {
            trigger: 'item'
        },
        legend: {
            top: '5%',
            left: 'center'
        },
        series: [
            {
                name: '数量',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 40,
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: echartsArr
            }
        ]
    }


    //获取文章列表
    useEffect(() => {
        const getData = async () => {
            const result = await reqGetEchartsArticleList()
            const arr = []
            // const newarr = [
            //     {name: 'IOS', value: 10},
            //     {name: '后端', value: 1},
            //     {name: '前端', value: 3},
            //     {name: '开发工具', value: 1},
            //     {name: '人工智能', value: 1}
            // ]
            Object.keys(result.data).forEach(name => {
                const value = result.data[name];
                arr.push({name, value}); // 向数组中新增一个元素，其name属性为对象属性名，value属性为对象属性值
            });
            setEchartsArr(arr)
        }
        getData()
    }, [])


    useEffect(() => {
        if (chartRef.current) {
            const myChart = echarts.init(chartRef.current);
            myChart.setOption(option)
        }
    }, [option, echartsArr])

    return (
        <div>
            <h1>文章数量</h1>
            <div ref={chartRef} style={{width: 800, height: 500}}></div>
        </div>
    );
};

export default ArtcileChart;